<?php

namespace app\common;

class Sign {

    public static function encode(array $payload, $key, $alg = 'SHA1') {
        $key = md5($key);
        $header64 = self::urlsafe_b64encode(json_encode(['typ' => 'JWT', 'alg' => $alg]));
        $payload64 = self::urlsafe_b64encode(json_encode($payload));
        $jwt = $header64 . '.' . $payload64;
        return $payload64 .self::signature($jwt, $key, $alg);
    }

    public static function decode($jwt,$key)
    {
        $key    = md5($key);
        $payload64 = substr($jwt, 0,strlen($jwt)-40);
        $sign = substr($jwt, strlen($jwt)-40);
        $header64 = self::urlsafe_b64encode(json_encode(['typ' => 'JWT', 'alg' => 'SHA1']));
        $header = json_decode(self::urlsafe_b64decode($header64), JSON_OBJECT_AS_ARRAY);

        if (empty($header['alg']))
            return false;

        if (self::signature($header64 . '.' . $payload64, $key, $header['alg']) !== $sign)
            return false;

        $payload = json_decode(self::urlsafe_b64decode($payload64), JSON_OBJECT_AS_ARRAY);

        $time = time();
        if (isset($payload['iat']) && $payload['iat'] > $time)
            return false;

        if (isset($payload['exp']) && $payload['exp'] < $time)
            return false;

        return $payload;
    }

    public static function signature($input, $key, $alg) {
        return hash_hmac($alg, $input, $key);
    }

    public static function urlsafe_b64decode($string) {

        $data = str_replace(array('-', '_'), array('+', '/'), $string);

        $mod4 = strlen($data) % 4;

        if ($mod4) {

            $data .= substr('====', $mod4);
        }

        return base64_decode($data);
    }

    public static function urlsafe_b64encode($string) {

        $data = base64_encode($string);

        $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);

        return $data;
    }
}
